﻿using OSGeo.OGR;
using RemoteSensingImageDirectServer.Untils.Pool;
using RemoteSensingImageDirectServer.Untils.ScopeSpace;

namespace RemoteSensingImageDirectServer.Untils.Extensions
{
    public static class OgrExtensions
    {
        public static RasterEnvelope Transform(this RasterEnvelope env, int srcepsg, int dstepsg)
        {
            var tileWkt = string.Format("POLYGON (({0} {1},{2} {3},{4} {5},{6} {7},{8} {9}))",
                                     env.MinX, env.MaxY,
                                     env.MaxX, env.MaxY,
                                     env.MaxX, env.MinY,
                                     env.MinX, env.MinY,
                                     env.MinX, env.MaxY);

            var tileGeom = Ogr.CreateGeometryFromWkt(ref tileWkt, OsrTransformPool.Instance().GetSRFromEPSG(srcepsg));
            tileGeom.SwapXY();
            tileGeom.TransformTo(OsrTransformPool.Instance().GetSRFromEPSG(dstepsg));
            var pEnvelope = new RasterEnvelope();
            tileGeom.GetEnvelope(pEnvelope);

            double rowCount = (env.MaxY - env.MinY) / env.ResolutionY;
            double colCount = (env.MaxX - env.MinX) / env.ResolutionX;

            pEnvelope.ResolutionX = (pEnvelope.MaxX - pEnvelope.MinX) / colCount;
            pEnvelope.ResolutionY = (pEnvelope.MaxY - pEnvelope.MinY) / rowCount;

            return pEnvelope;
        }

        public static void Free(this DataSource ds) 
        {
            if (ds == null) return;
            ds.Close();
            ds.Dispose();
        }

    }
}
